package com.tengju.motivation.application.performance;

import com.tengju.motivation.application.activity.MotivationActivityConfigService;
import com.tengju.motivation.application.performance.dto.ChunMiaoPlanUserTargetForm;
import com.tengju.motivation.application.shared.ApplicationException;
import com.tengju.motivation.domain.model.performance.*;
import com.tengju.motivation.domain.shared.DateUtil;
import com.tengju.motivation.domain.shared.PerformanceObjectiveType;
import com.tengju.motivation.domain.shared.Year;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 李大仙
 * @date: 2021/5/15 4:35 下午
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MotivationPerformanceObjectiveService {

    private final PerformanceObjectiveRepository performanceObjectiveRepository;
    private final MotivationActivityConfigService motivationActivityConfigService;

//    @Value("#{${import.template.map}}")
//    private Map<String, String> importTemplateMap;


    @Transactional(rollbackFor = Exception.class)
    public void updateChunMiaoTarget(ChunMiaoPlanUserTargetForm chunMiaoTargetForm, String updateBy){
        Year year = new Year(String.valueOf(chunMiaoTargetForm.getDateForYear()));
        int startTime = DateUtil.getDayIntByLocalDate(year.getYearStartDate());
        int endTime = DateUtil.getDayIntByLocalDate(year.getYearEndDate());
        ChunMiaoTarget chunMiaoTarget = new ChunMiaoTarget(new PerformanceObjectiveObjectId(chunMiaoTargetForm.getIdCode()),
                chunMiaoTargetForm.getDateForYear(),
                chunMiaoTargetForm.getProfitTarget(),
                Long.parseLong(String.valueOf(chunMiaoTargetForm.getUpgradeTarget())),
                chunMiaoTargetForm.getDealerPullTarget(),
                chunMiaoTargetForm.getSvipPullTarget(),
                chunMiaoTargetForm.getVvipPullTarget(),
                chunMiaoTargetForm.getCrowdDealerCntTarget());
        List<PerformanceObjective> chunMiaoUserTarget = PerformanceObjectiveFactory.createChunMiaoUserTarget(chunMiaoTarget, updateBy);
        List<String> keys = Arrays.stream(ChunMiaoTargetEnum.values()).map(ChunMiaoTargetEnum::getKey).collect(Collectors.toList());
        // 更新采用先删除后新增的方式
        performanceObjectiveRepository.batchRemoveByIdCodeAndKeysAndType(chunMiaoTarget.getIdCode(), keys, PerformanceObjectiveTypeEnum.CHUN_MIAO_PLAN_USER, startTime, endTime);
        performanceObjectiveRepository.batchAdd(chunMiaoUserTarget);
    }

    public int add(Long objectId, Integer type, String key, String name, String desc, Integer value, Integer startTime, Integer endTime, String staffName) {
        PerformanceObjective performanceObjective = PerformanceObjectiveFactory.create(objectId,
                type, key, name, desc, value, startTime, endTime, staffName);
        return performanceObjectiveRepository.add(performanceObjective);
    }

    public int remove(List<Long> idList) {
        List<PerformanceObjectiveId> performanceObjectiveIds = idList.stream()
                .map(PerformanceObjectiveId::new)
                .collect(Collectors.toList());
        return performanceObjectiveRepository.remove(performanceObjectiveIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importPerformanceObjective(List<String[]> rows, Integer type, String operatorName) {
        PerformanceObjectiveTypeEnum performanceObjectiveTypeEnum = PerformanceObjectiveTypeEnum.form(type);
        if (performanceObjectiveTypeEnum == null) {
            throw ApplicationException.error("绩效目标类型不正确");
        }
        Map<String, Integer> map = new HashMap<>();

        int lineNumber = 1;
        String realTime = "";
        Integer startTime = null;
        Integer endTime = null;

        List<PerformanceObjective> performanceObjectives = new ArrayList<>();
        for (String[] cells : rows) {
            lineNumber++;
            String time = cells[0];
            if (StringUtils.isEmpty(time)) {
                throw ApplicationException.error("第" + lineNumber + "行日期为空");
            }
            if (time.length() != 6) {
                throw ApplicationException.error("第" + lineNumber + "行日期格式不正确");
            }
            if (StringUtils.isEmpty(realTime)) {
                realTime = time;
            } else {
                if (!realTime.equals(time)) {
                    throw ApplicationException.error("第" + lineNumber + "行日期不一致");
                }
            }
            String secIdCodeVal = cells[1];
            if (StringUtils.isEmpty(secIdCodeVal)) {
                throw ApplicationException.error("第" + lineNumber + "行SEC用户ID为空");
            }
            String performanceObjectiveName = cells[2];
            if (StringUtils.isEmpty(performanceObjectiveName)) {
                throw ApplicationException.error("第" + lineNumber + "行目标名称为空");
            }
            if (!PerformanceObjectiveType.getTargetDescList().contains(performanceObjectiveName)) {
                throw ApplicationException.error("第" + lineNumber + "行目标名称不正确");
            }
            String performanceObjectiveVal = cells[3];
            if (StringUtils.isEmpty(performanceObjectiveVal)) {
                throw ApplicationException.error("第" + lineNumber + "行目标值为空");
            }
            String key = secIdCodeVal + "_" + performanceObjectiveName;
            if (map.containsKey(key)) {
                throw ApplicationException.error("第" + lineNumber + "行与第" + map.get(key) + "行配置重复");
            } else {
                map.put(key, lineNumber);
            }
            if (startTime == null || endTime == null) {
                startTime = getStartTime(realTime);
                endTime = getEndTime(realTime);
            }

            PerformanceObjectiveType performanceObjectiveType = PerformanceObjectiveType.getByTargetDesc(performanceObjectiveName);
            performanceObjectives.add(PerformanceObjectiveFactory.create(Long.valueOf(secIdCodeVal),
                    performanceObjectiveTypeEnum.getCode(),
                    performanceObjectiveType.getCode(),
                    performanceObjectiveType.getDesc(),
                    "",
                    Integer.valueOf(performanceObjectiveVal),
                    startTime,
                    endTime,
                    operatorName
            ));
        }
        if (!CollectionUtils.isEmpty(performanceObjectives)) {
            // 先删除同类型同时间段的绩效目标，再保存新的绩效目标
            performanceObjectiveRepository.batchRemove(performanceObjectiveTypeEnum, startTime, endTime);
            performanceObjectiveRepository.batchAdd(performanceObjectives);
        }
    }

    public String getPerformanceObjectiveTemplate() {
//        return importTemplateMap.get("performanceObjectiveTemplate");
        return "";
    }

    private Integer getEndTime(String time) {
        if (DateUtil.QUARTER_SIGN.equalsIgnoreCase(String.valueOf(time.charAt(4)))) {
            LocalDateTime quarterMax = DateUtil.getQuarterMax(time);
            return DateUtil.getMonthInt(quarterMax);
        } else {
            return Integer.valueOf(time);
        }
    }

    private Integer getStartTime(String time) {
        if (DateUtil.QUARTER_SIGN.equalsIgnoreCase(String.valueOf(time.charAt(4)))) {
            LocalDateTime quarterMin = DateUtil.getQuarterMin(time);
            return DateUtil.getMonthInt(quarterMin);
        } else {
            return Integer.valueOf(time);
        }
    }
}